package com.lanfan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanfan.entity.Todaymenu;
import com.lanfan.entity.TodaymenuExample;
import com.lanfan.entity.TodaymenuPage;
import com.lanfan.mapper.TodaymenuMapper;
import com.lanfan.service.TodaymenuService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class TodaymenuServiceImpl implements TodaymenuService {
    @Resource
    private TodaymenuMapper todaymenuMapper;

    @Override
    public List<Todaymenu> getTodaymenuList(){
        return todaymenuMapper.selectByExample(null);
    }
    @Override
    public boolean increasePopularity(Integer tid) {
        return todaymenuMapper.increasePopularity(tid) > 0;
    }
    @Override
    public List<Todaymenu> searchMenusExact(String keyword) {
        return todaymenuMapper.searchMenusExact(keyword);
    }
    //admin
    @Override
    public void save(Todaymenu todaymenu) {
        if(todaymenu.getTid()!=null){
            update(todaymenu);
        }else {
            insert(todaymenu);
        }
    }
    private void update(Todaymenu todaymenu){
        todaymenuMapper.updateByPrimaryKey(todaymenu);
    }
    private void insert(Todaymenu todaymenu){
        todaymenuMapper.insert(todaymenu);
    }

    @Override
    public void delete(Integer tid) {
        todaymenuMapper.deleteByPrimaryKey(tid);
    }

    @Override
    public void search(TodaymenuPage todaymenuPage) {
        //当前页码 ，每页的记录数
        /*
        startPage方法生成sql片段 给第一条sql语句拼接limit

        页码 ：1
        每页记录数：5
        limit 0,5
         */
        PageHelper.startPage(todaymenuPage.getPageIndex(),todaymenuPage.getPageSize());
        TodaymenuExample todaymenuExample=new TodaymenuExample();
        TodaymenuExample.Criteria criteria=todaymenuExample.createCriteria();

        if (!StringUtils.isEmpty(todaymenuPage.getDishName())) {
            criteria.andDishNameLike("%"+todaymenuPage.getDishName()+"%");
        }

        List<Todaymenu> todaymenus = todaymenuMapper.selectByExample(todaymenuExample);
        //分页插件的 PageInfo 和Page类 一样 5个属性
        PageInfo<Todaymenu> pageInfo=new PageInfo<>(todaymenus);
        todaymenuPage.setTotal((int)pageInfo.getTotal());
        todaymenuPage.setList(todaymenus);


    }

    @Override
    public void deleteTodaymenus(Integer[] tids) {
        TodaymenuExample todaymenuExample=new TodaymenuExample();
        TodaymenuExample.Criteria criteria = todaymenuExample.createCriteria();
        criteria.andTidIn(Arrays.asList(tids));
        todaymenuMapper.deleteByExample(todaymenuExample);
    }


}
